package com.shopping.handler;

import com.alibaba.fastjson2.JSONObject;
import com.shopping.commons.CurUserInfo;
import com.shopping.commons.Result;
import com.shopping.model.UserInfo;
import com.shopping.utils.JWTUtils;
import com.shopping.utils.RSAUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;


/**
 * 登陆成功处理器，该处理器实现AuthenticationSuccessHandler
 *  当用户登陆成功后会自动执行该处理器里的onAuthenticationSuccess方法
 */
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //设置响应类型及编码集
        response.setContentType("application/json;charset=utf-8");
        try {
            //获得认证对象获得认证主体，主体式User对象
            User user= (User) authentication.getPrincipal();

            //将用户名转化为UserInfo对象
            //user.getUsername存放有用户信息，将该信息转换为UserInfo对象
            UserInfo userInfo = JSONObject.parseObject(user.getUsername(), UserInfo.class);
            //将userInfo中的数据转存到CurUserInfo中
            CurUserInfo curUserInfo=new CurUserInfo();
            curUserInfo.setUser_id(userInfo.getUser_id());
            curUserInfo.setUser_name(userInfo.getUser_name());

            //删除SecurityContextHolder
            SecurityContext context = SecurityContextHolder.createEmptyContext();
            SecurityContextHolder.setContext(context);
            //读取私钥
            PrivateKey privateKey = RSAUtils.getPrivateKey("D:\\Java源码\\demo\\shopping\\myshopping-project-server\\src\\main\\resources\\Keys\\key.private");
            Map<String,Object> payloadMap =new HashMap<>();
            payloadMap.put("curUserInfo",curUserInfo);
            payloadMap.put("authorities",user.getAuthorities());

            //登陆成功签发
            String token = JWTUtils.generateToken(payloadMap, privateKey, 60*60*24*7);
            Map<String,Object>  map =new HashMap<>();
            map.put("token",token);
            map.put("curUserInfo",curUserInfo);


            Result result =Result.success("登陆成功",map);
            response.getWriter().println(JSONObject.toJSONString(result));
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
}
